package com.base.myproject.client.HR.Training;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseTreeStore;
import com.base.myproject.client.busi.Editdisable;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Label;

public class Training_MonthlyCalendar extends BaseJDBCPanel{
	
	String treeDepId = null;                       //将当前树形结构中选中的部门id保存
	String treeDepName = null;                     //将当前树形结构中选中的部门name保存
	TreePanel<TreeNodeModelData> treepanel = null;
	BaseComboBoxForm<BaseModelData> sectionCode = new BaseComboBoxForm<BaseModelData>("id","name","SystemInfo","where name is not null and id is not null and len(id)=(select max(len(id)) from systeminfo)",true);
	Button btnAdd = null;
	Button btnDelete = null;
	Button btnImport = null;
	StoreFilterField field = null;   
	BaseFormPanel form = null;
	String results = null;
	String bcode = Env.getEnvbcode();
	
	public Training_MonthlyCalendar(){
		String sql = "select substring('id like '''+replace(permissionsbcode,';','%'' or id like '''),9," +
		"len('id like '''+replace(permissionsbcode,';','%'' or id like '''))-21) as result from" +
		" busipermissions where bcode = '"+bcode+"' and busicode = 8010";
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService2.getDataSet(sql, new AsyncCallback<DataSet>(){
		@Override
			public void onFailure(Throwable caught) {	
			}
			@Override
			public void onSuccess(DataSet result) {  
			   results = result.getValue(0, "result");
			   init();
			}
		});
	}
	
	public void complete(){
		super.complete();
	}
	
	public void init(){
		initWidget();
    	registerMainStore(store1);
		registerStore(store1);
	}
	
	public void initWidget(){
		HorizontalPanel cp = new HorizontalPanel();
		VerticalPanel vp = new VerticalPanel();		
		HorizontalPanel s = new HorizontalPanel();
		VerticalPanel v = new VerticalPanel();	
		HorizontalPanel hp = new HorizontalPanel();
		s.setHeight("25");
		vp.add(this.createQuery());
		v.add(this.createForm());
		v.add(this.createToolBar());
		hp.add(this.getGrid1());
		hp.add(v);
		vp.add(hp);
		cp.add(getTreePanel());
		cp.add(vp);
		cp.setStyleName("hp_css");//添加一个css属性
		add(cp);
		this.layout();
	}
	
	BaseTreeStore<TreeNodeModelData> treeStore = null;
	private TreePanel<TreeNodeModelData> getTreePanel(){
		if(treepanel == null){
			initTreePanel();
		}
		return treepanel;
	}
	
	private BaseTreeStore<TreeNodeModelData> getTreeStore(){
		if (treeStore == null) {
			initTreeStore();
		}
		return treeStore;
	}
	
	private BaseTreeStore<TreeNodeModelData> initTreeStore(){
		StoreInfo info = new StoreInfo();
		String sql2 = "select icode,id,name from SystemInfo where id like "+results+" order by id asc";
		info.setSql(sql2);
		info.setTreesortcolumn("id");
		info.setKeyname(new String[]{ "icode" });
		info.setTablename("SystemInfo");
		treeStore = new BaseTreeStore<TreeNodeModelData>(info,false);
		treeStore.load();
		return treeStore;
	}
	
	private void initTreePanel(){
		treepanel = new TreePanel<TreeNodeModelData>(getTreeStore());
		treepanel.setSize(150, 450);
		treepanel.setBorders(true);
		treepanel.setDisplayProperty("name");
		treepanel.setCheckStyle(CheckCascade.PARENTS);
		treepanel.setCheckNodes(CheckNodes.BOTH);
		treepanel.setCheckable(false);
		treepanel.setAutoLoad(true);
		treepanel.setCaching(true);
		
		treepanel.addListener(Events.OnClick,
			new Listener<TreePanelEvent<TreeNodeModelData>>() {
				public void handleEvent(TreePanelEvent<TreeNodeModelData> be) {
					if(be.getItem().getChildCount() == 0){
						String id = be.getItem().get("id").toString();
						treeDepId=id;
						treeDepName=be.getItem().get("name").toString();
						set_Grid(id);
					}
				}
			});
	}
	public void set_Grid(String id){
		StoreInfo info2 = new StoreInfo();
		info2.setTablename("hr_TrainingMonthlyCalendar");//("hr_YearlyTrainingPlan");
		info2.setKeyname(new String[] { "icode" });
		String where=" where 1=1 and ";
		if(id.length()<5){
			where=where+" sectionCode like '" +id+ "%25'";
		}else{
			where=where+" sectionCode = '" +id+ "'";
		}
		info2.setSql("select * from hr_TrainingMonthlyCalendar "+where);//这里sql的linke %%  有问题
		grid1.getStore().setStoreinfo(info2);
		grid1.getStore().reload();
		grid1.getView().refresh(true);
    }
	
	private FieldSet createQuery(){
		FieldSet query = new FieldSet();
		query.setHeading("查询操作");
		
		HorizontalPanel s=new HorizontalPanel();
		s.setHeight("20");
		
		s.add(new Label("快速查询: "));
		cread_field();
		s.add(field);
		query.add(s);
		return query;
	}
	
	BaseStore<BusiObject> store = null;
	public BaseStore<BusiObject> getStore(){
		if(store == null){
			createStore();
		}
		return store;
	}
	
	ModelType type = new ModelType();
	private BaseStore<BusiObject> createStore(){
		
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		
		type.addField("sectionCode");
		type.getField("sectionCode").setType(String.class);
		
		type.addField("yearMonth");
		type.getField("yearMonth").setType(Date.class);
		
		type.addField("approvedBy");
		type.getField("approvedBy").setType(String.class);
		
		type.addField("creater");
		type.getField("creater").setType(String.class);
		
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_TrainingMonthlyCalendar");
		info.setKeyname(new String[] { "icode"});
		info.setSql("select * from hr_TrainingMonthlyCalendar where yearMonth = '{yearMonth}' and sectionCode = '{sectionCode}'");
		info.setParent(getStore1());
		info.setLinkparentcolumns(new String[] { "yearMonth","sectionCode" }); // 关联主表字段
		info.setLinkparent_chile_columns(new String[] { "yearMonth","sectionCode"  });// 关联子表字段
		store = new BaseStore<BusiObject>(type, info);
		return null;
	}
	
	DateField month = null;
	private BaseFormPanel createForm(){
		form = new BaseFormPanel(getStore(),false);
		form.setHeaderVisible(false);
		
		TableLayout t = new TableLayout(8);
		TableData td = new TableData();
		form.setLayout(t);
		
		form.add(new Label("月份："),td);
		month = new DateField();
		month.setName("yearMonth");
		month.setWidth(80);
		month.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-MM"));
		form.add(month,td);
		
		form.add(new Label("分部门："),td);
		sectionCode.setReadOnly(true);
		sectionCode.setName("sectionCode");
		sectionCode.setWidth(100);
		form.add(sectionCode,td);
		
		form.add(new Label("制表人："),td);
		TextField<String> creater = new TextField<String>();
		creater.setName("creater");
		creater.setWidth(100);
		form.add(creater,td);
		
		form.add(new Label("审批人："),td);
		TextField<String> approvedBy = new TextField<String>();
		approvedBy.setName("approvedBy");
		approvedBy.setWidth(100);
		form.add(approvedBy,td);
		
		form.inited();
		return form;
	}
	
	BaseStore<BusiObject> store1 = null;
	public BaseStore<BusiObject> getStore1(){
		if(store1 == null){
			createStore1();
		}
		return store1;
	}
	private BaseStore<BusiObject> createStore1(){
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		
		type.addField("sectionCode");
		type.getField("sectionCode").setType(String.class);
		
		type.addField("yearMonth");
		type.getField("yearMonth").setType(Date.class);
		
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_TrainingMonthlyCalendar");
		info.setKeyname(new String[] { "icode"});
		info.setSql("select * from hr_TrainingMonthlyCalendar where 1=2");
		store1 = new BaseStore<BusiObject>(type, info);
		//DateTimeFormat activeFormat = DateTimeFormat.getFormat("yyyy-MM");
		store1.addDefault("yearMonth", new Date());
		return null;
	}
	
	BaseGrid grid1 = null;
	public BaseGrid getGrid1() {
		if (grid1 == null) {
			createGrid1();
		}
		return grid1;
	}
	
	private void createGrid1(){
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		DateField dateField1 = new DateField();
		
		ColumnConfig C5 = new ColumnConfig("yearMonth", "年月", 60);
		C5.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM"));
		columns.add(C5);
		
		ColumnConfig C3 = new ColumnConfig("sectionCode", "分部门", 80);
		sectionCode.setReadOnly(true);
		sectionCode.setName("sectionCode");
		C3.setRenderer(sectionCode);
		C3.setEditor(sectionCode.getCelEditor());
		columns.add(C3);
		
		ColumnModel cm = new ColumnModel(columns);
		grid1 = new BaseGrid(getStore1(), cm){
			@SuppressWarnings("unchecked")
			public void addnewrecord() {
				if (treeDepId == null ) {
					MessageBox.alert("警告", "请选择一个部门后再添加新信息", null);
					return;
				}
				HashMap hp = new HashMap();
				hp.put("sectionCode", treeDepId);
				grid1.getStore().add(hp);
			}
		};
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid1.setSelectionModel(cbs);
		Tools.setResize(grid1,0.17,0.82);
	}
	
	BaseStore<BusiObject> store2 = null;
	public BaseStore<BusiObject> getStore2(){
		if(store2 == null){
			createStore2();
		}
		return store2;
	}
	private BaseStore<BusiObject> createStore2(){
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		
		type.addField("micode");
		type.getField("micode").setType(Long.class);
		
		type.addField("trainingDate");
		type.getField("trainingDate").setType(Date.class);
		
		type.addField("content");
		type.getField("content").setType(String.class);
		
		type.addField("readOnly");
		type.getField("readOnly").setType(String.class);
		
		type.addField("YearlyTrainingPlan_icode");
		type.getField("YearlyTrainingPlan_icode").setType(Long.class);
		
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_TrainingMonthlyCalendar_list");
		info.setKeyname(new String[] { "icode"});
		info.setSql("select * from hr_TrainingMonthlyCalendar_list where micode = '{icode}' ");
		info.setParent(getStore1());
		info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
		info.setLinkparent_chile_columns(new String[] { "micode"  });// 关联主表字段
		store2 = new BaseStore<BusiObject>(type, info);
		store2.addEditdisableItem(new Editdisable("readOnly","1",BaseStore.EditDisableType.EQUALS));
		return null;
	}
	
	ContentPanel panel = null;
	private ContentPanel createToolBar(){
		panel = new ContentPanel();
		panel.setHeaderVisible(false);
		ToolBar toolbar = new ToolBar();
		btnAdd = new Button("添加");
		btnDelete = new Button("删除");
		btnImport = new Button("导入年度计划");
		btnAdd.addListener(Events.OnClick, getListener());
		btnDelete.addListener(Events.OnClick, getListener());
		btnImport.addListener(Events.OnClick, getListener());
		btnAdd.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.addrecord()));
		btnDelete.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.deleterecord())); 
		toolbar.add(btnAdd);
		toolbar.add(btnDelete);
		toolbar.add(btnImport);
		panel.setTopComponent(toolbar);
		panel.add(getGrid2());
		return panel;
	}
	
	BaseGrid grid2 = null;
	public BaseGrid getGrid2() {
		if (grid2 == null) {
			createGrid2();
		}
		return grid2;
	}
	
	private void createGrid2(){
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		DateField dateField1 = new DateField();
		
		ColumnConfig C5 = new ColumnConfig("trainingDate", "日期", 100);
		C5.setDateTimeFormat(DateTimeFormat.getFormat("MM-dd"));
		columns.add(C5);
		
		ColumnConfig C7 = new ColumnConfig("content", "内容", 400);
		TextField<String> content = new TextField<String>();
		content.setName("content");
		C7.setEditor(new CellEditor(content));
		columns.add(C7);
		
		ColumnModel cm = new ColumnModel(columns);
		grid2 = new BaseGrid(getStore2(), cm,false,false);
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid2.setSelectionModel(cbs);
		Tools.setResize(grid2,0.60,0.655);
	}
	
	protected boolean Select(Store<BusiObject> store,
			BusiObject parent, BusiObject record, String property,
			String filter) {
		for (int i = 0; i < type.getFieldCount(); i++) {
			Object name = record.get(type.getField(i).getName());
			if (name!=null&&name.toString().indexOf(filter.toLowerCase()) != -1) {
				return true;
			}
		}
		return false;
	}	
	
	public void cread_field(){
		field = new StoreFilterField<BusiObject>() {
			@Override
			protected boolean doSelect(Store<BusiObject> store,
					BusiObject parent, BusiObject record, String property,
					String filter) {

			return	Select(store,parent,record,property,filter);
			}
			@Override
			protected void onFilter() {
				super.onFilter();
				// grid.getSelectionModel().select(0);
			}
		};
		field.setAutoWidth(true);
		field.setToolTip("对当前部门数据进行查找");
		field.bind(getStore());
		this.field = field;
	}
	
	int sync = 0;                                                      
	Listener<BaseEvent> defaultlistener;                               
                                                                     
	public Listener<BaseEvent> getListener() {                                
		if(defaultlistener!=null)                                        
		{                                                                
			return defaultlistener;                                        
		}                                                                
                                                                     
		defaultlistener = new Listener<BaseEvent>() {                    
			public void handleEvent(BaseEvent be) {                        
				sync++;                                                    
				try {                                                      
					if (sync == 1) {                                   
						if (be.getType() == Events.Select) { 
							
						}else if(be.getType() == Events.OnBlur){
							
						}else if(be.getType() == Events.OnClick){
							if(be.getSource().equals(btnAdd)){
								if(treeDepId == null){
									MessageBox.alert("提示", "请选择分部门！", null);
								}else if(getStore1().getCount() == 0){
									MessageBox.alert("提示", "请添加月份", null);
								}else{
									Long micode = Long.parseLong(getStore1().getValue("icode").toString());
									Date time = (Date)getStore1().getValue("yearMonth");
									int month = time.getMonth() + 1;
									int year = time.getYear() + 1900;
//									Calendar calendar = Calendar .getInstance();
//									calendar.clear();
//									calendar.set(Calendar.YEAR,year);
//									calendar.set(Calendar.MONTH, year);
//									int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
									if(time == null){
										MessageBox.alert("提示", "请选择月份！", null);
									}else if(getStore2().getCount() != 0){
										MessageBox.alert("提示", "对应的月份已有数据，请重新选择月份！", null);
									}else{
										int secondM = 0;
										if(year%4 == 0 && ( year%100 != 0 || year%400 == 0)){
											secondM = 29;
										}else{
											secondM= 28; 
										}
										if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
											for(int i = 1;i < 32; i++){
												String times = year + "-" + month + "-" + i;
												BusiObject bo = new BusiObject();
												bo.set("micode", micode);
												bo.set("trainingDate", dateFormat(times));
												getStore2().add(bo);
											}
										}else if(month == 4 || month == 6 || month == 9 || month == 11){
											for(int i = 1;i < 31; i++){
												String times = year + "-" + month + "-" + i;
												BusiObject bo = new BusiObject();
												bo.set("micode", micode);
												bo.set("trainingDate", dateFormat(times));
												getStore2().add(bo);
											}
										}else{
											for(int i = 1;i < secondM + 1; i++){
												String times = year + "-" + month + "-" + i;
												BusiObject bo = new BusiObject();
												bo.set("micode", micode);
												bo.set("trainingDate", dateFormat(times));
												getStore2().add(bo);
											}
										}
									}
								}
								
							}else if(be.getSource().equals(btnDelete)){
								Long micode1 = Long.parseLong(getStore1().getValue("icode").toString());
								if(micode1 == 0){
									MessageBox.alert("提示", "请选择部门对应的月份！", null);
								}else{
									String sql = "delete from hr_TrainingMonthlyCalendar_list where micode = "+micode1;
									save_sql(sql);
									grid1.getStore().reload();
								}
							}else if(be.getSource().equals(btnImport)){
								if(treeDepId == null){
									MessageBox.alert("提示", "请选择分部门！", null);
								}else if(getStore1().getCount() == 0){
									MessageBox.alert("提示", "请添加月份", null);
								}else{
									Long micode = Long.parseLong(getStore1().getValue("icode").toString());
									Date time = (Date)getStore1().getValue("yearMonth");
									String sectioncode = getStore1().getValue("sectionCode").toString();
									int month = time.getMonth() + 1;
									int year = time.getYear() + 1900;
									String times = null;
									if(month < 10){
										times = year + "-" + 0 + month;
									}else{
										times = year + "-" + month;
									}
									if(time == null){
										MessageBox.alert("提示", "请选择月份！", null);
									}else{
										String sqlimport = "update hr_TrainingMonthlyCalendar_list set content = " +
												"(select topic from hr_YearlyTrainingPlan_list where substring(convert(char(20)," +
												"YearMonth,121),0,8) = '"+times+"'"+
												"and exists(select sectioncode from hr_TrainingMonthlyCalendar where sectioncode = '"+sectioncode+"'))," +
												"YearlyTrainingPlan_icode = (select icode from hr_YearlyTrainingPlan_list " +
												"where substring(convert(char(20),YearMonth,121),0,8) = '"+times+"' and " +
												"exists(select sectioncode from hr_TrainingMonthlyCalendar " +
												"where sectioncode = '"+sectioncode+"'))," +
												"readOnly = 1 where micode = '"+micode+"'";
										save_sql(sqlimport);
										grid1.getStore().reload();
										grid1.getView().refresh(true);
									}
								}
								
							}
						} else if (be.getType() == Events.Changed){
							
						}else if (be.getType() == Events.KeyUp) { 
							if (be instanceof ComponentEvent) {                    
								if (((ComponentEvent)be).getKeyCode() == 13){       // 回车                    
								}                          
							}                                  
						}                                          
					}                                                  
				} finally {                                                
					sync--;                                            
				}                                                          
			}                                                              
		};                                                               
		return defaultlistener;                                          
	}
	
	public Date dateFormat(String date){
		Date df_date = new Date();
		String[] strdates = date.split("-");
		int year = Integer.parseInt(strdates[0]);
		int month = Integer.parseInt(strdates[1]);
		int day = Integer.parseInt(strdates[2]);
		df_date.setYear(year-1900);
		df_date.setMonth(month-1);
		df_date.setDate(day);
		return df_date;
	}
	
	private boolean  save_sql(String sql){
		CommandSyncsql csql = new CommandSyncsql();//执行sql命令
		String delsql =sql;
		csql.getV().add(delsql);
		if(csql.getV().size()<=0){
			return false;
		}else{
			CommandSyncContainer list = new CommandSyncContainer();//可以添加的命令
			 list.add(csql);
		
			 GreetingServiceAsync greetingService = GWT
				.create(GreetingService.class);
			 greetingService
				.SendCommandSync(
						list,
						new AsyncCallback<CommandSyncReturnObject>() {
							@Override
							public void onFailure(
									Throwable caught) {
								MessageBox.alert("错误",
										"网络连接失败", null);
							}
							@Override
							public void onSuccess(
									CommandSyncReturnObject result) {
								if (result.isB()) {
									Info.display("提示信息", "添加成功");								
								}
								else{
									MessageBox.alert("错误",
											"错误，错误代码"+result.getMessage(), null);
								}
							}
						});
		}
		return true;
	}	
}
